package com.article.controller.system;

import com.article.dto.ReturnError;
import com.article.enums.ReturnInfoEnum;
import com.article.model.AdminInfo;
import com.article.model.ArticleInfo;
import com.article.model.ArticleType;
import com.article.service.ArticleInfoService;
import com.article.service.ArticleTypeService;
import com.article.utils.StringUtil;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * Created by Administrator on 2017/5/3.
 */
@RestController
@RequestMapping("/articleAdmin")
public class ArticleAdminController {
    private final static byte[] lock = new byte[0]; // 特殊的instance变量
    private final static Logger logger = LoggerFactory.getLogger(ArticleAdminController.class);
    @Autowired
    private ArticleInfoService articleInfoService;
    @Autowired
    private ArticleTypeService articleTypeService;

    /**
     * 文章列表
     *
     * @param key
     * @param pageIndex
     * @param limit
     * @return
     */
    @RequestMapping(value = "/listArticle", method = RequestMethod.POST)
    public ReturnError listArticle(@RequestParam(name = "key", required = false) String key,
                                   @RequestParam(name = "pageIndex", required = true, defaultValue = "0") Integer pageIndex,
                                   @RequestParam(name = "limit", required = true, defaultValue = "10") Integer limit) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<ArticleInfo> articleInfoList = new ArrayList<ArticleInfo>();
        try {
            if (StringUtil.isNotEmpty(key)) {
                map.put("titleLike", key);
            }
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            AdminInfo adminInfo = (AdminInfo) session.getAttribute("adminLogin");
            if (adminInfo.getRoleId().longValue() != 1) {
                map.put("adminId", adminInfo.getId());
            }
            PageInfo<ArticleInfo> p = articleInfoService.listByPage(pageIndex + 1, limit, map);
            return new ReturnError(false, ReturnInfoEnum.SUCCESS.getType(), p.getTotal(), p.getList());
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getInfo(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), 0L, null);
        }
    }

    @RequestMapping(value = "/saveArticle", method = RequestMethod.POST)
    public ReturnError saveArticle(ArticleInfo articleInfo) {
        try {
            if (StringUtil.isEmpty(articleInfo.getTitle())) {
                return new ReturnError(true, ReturnInfoEnum.EMPTY.getType(), "请输入标题");
            }
            if (StringUtil.isEmpty("" + articleInfo.getTypeId())) {
                return new ReturnError(true, ReturnInfoEnum.EMPTY.getType(), "选择文章类别");
            }
            if (StringUtil.isEmpty(articleInfo.getContent())) {
                return new ReturnError(true, ReturnInfoEnum.EMPTY.getType(), "请输入内容");
            }
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            AdminInfo adminInfo = (AdminInfo) session.getAttribute("adminLogin");
            articleInfo.setAdminId(adminInfo.getId());
            articleInfo.setClickHit(0);
            articleInfo.setReplyHit(0);
            articleInfo.setGmtCreate(Calendar.getInstance().getTime());
            articleInfo.setGmtModified(articleInfo.getGmtCreate());
            return articleInfoService.saveArticle(articleInfo);
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getInfo(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), ReturnInfoEnum.ERROR.getInfo(), null);
        }
    }

    @RequestMapping(value = "/getArticle", method = RequestMethod.POST)
    public ReturnError getArticle(@RequestParam(value = "id", required = true) Long id) {
        try {
            ArticleInfo articleInfo = articleInfoService.getById(id);
            if (articleInfo == null) {
                return new ReturnError(true, ReturnInfoEnum.NORECORD.getType(), ReturnInfoEnum.NORECORD.getInfo(), null);
            }
            return new ReturnError(false, ReturnInfoEnum.SUCCESS.getType(), articleInfo);
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getInfo(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), ReturnInfoEnum.ERROR.getInfo(), null);
        }
    }

    /**
     * 修改文章
     *
     * @param id
     * @param articleInfo
     * @return
     */
    @RequestMapping(value = "/updateArticle", method = RequestMethod.POST)
    public ReturnError updateArticle(@RequestParam(name = "id", required = true) Long id, ArticleInfo articleInfo) {
        try {
            if (StringUtil.isEmpty(articleInfo.getTitle())) {
                return new ReturnError(true, ReturnInfoEnum.EMPTY.getType(), "请输入标题");
            }
            if (StringUtil.isEmpty("" + articleInfo.getTypeId())) {
                return new ReturnError(true, ReturnInfoEnum.EMPTY.getType(), "选择文章类别");
            }
            if (StringUtil.isEmpty(articleInfo.getContent())) {
                return new ReturnError(true, ReturnInfoEnum.EMPTY.getType(), "请输入内容");
            }
            ArticleInfo artInfo = articleInfoService.getById(id);
            if (artInfo == null) {
                return new ReturnError(true, ReturnInfoEnum.NORECORD.getType(), ReturnInfoEnum.NORECORD.getInfo(), null);
            }
            artInfo.setTitle(articleInfo.getTitle());
            artInfo.setTypeId(articleInfo.getTypeId());
            artInfo.setSummary(articleInfo.getSummary());
            artInfo.setContent(articleInfo.getContent());
            artInfo.setKeyWord(articleInfo.getKeyWord());
            artInfo.setGmtModified(Calendar.getInstance().getTime());
            return articleInfoService.updateArticle(artInfo);
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getInfo(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), ReturnInfoEnum.ERROR.getInfo(), null);
        }
    }

    /**
     * 删除文章
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/removeArticle", method = RequestMethod.POST)
    public ReturnError removeArticle(@RequestParam(name = "ids", required = true) String ids) {
        try {
            return articleInfoService.removeArticle(ids);
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getInfo(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), ReturnInfoEnum.ERROR.getInfo(), null);
        }
    }

    /**
     * 新增、修改页面初始化文章类型
     *
     * @return
     */
    @RequestMapping(value = "/listTypes")
    public ReturnError listTypes() {
        List<ArticleType> articleTypeList = new ArrayList<ArticleType>();
        Map<String, Object> resMap = new HashMap<String, Object>();
        try {
            articleTypeList = articleTypeService.listByMap(new HashMap<String, Object>());
            return new ReturnError(false, ReturnInfoEnum.SUCCESS.getType(), articleTypeList);
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getInfo(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), ReturnInfoEnum.ERROR.getInfo(), null);
        }
    }
}
